// pages/tiku/kaoti_index.js
//获取应用实例
const app = getApp()
//单选
var zuodaInfo = [];
//多选
var mulZuoDaInfo = [];
//试题汇总
var questionArrays1 = [];
//考试开始时间
var starttime = '';
//考试结束时间
var endtime = '';

//定时
var Interval = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: '',
    index: 0,
    testname: '',
    questionArrays: [],
    questionInfo: {},
    optionInfo: {},
    selectOption: "",
    mulSelectOption: "",
    testpaper_id: '',
    answer: '',
    score: '',
    //item_id: '',
    windowHeight: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    this.setData({
      index: 0
    });
    wx.getSystemInfo({
      success(res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth; //比例
        var calc = clientHeight * rpxR * 1.1;
        //console.log(calc)
        that.setData({
          windowHeight: calc
        });
      }
    })
    starttime = options.starttime;
    //console.log('考试开始时间'+starttime)
    this.setData({
      testpaper_id: options.testid,
      //item_id: options.xiangmuid,
      testname: options.testname
    });
    //单选
    var zuodaInfohc = wx.getStorageSync('zuodaInfo')
    //console.log('onLoad方法缓存中zuodaInfo的长度' + zuodaInfohc.length)
    if (zuodaInfohc.length > 0) {
      zuodaInfo = zuodaInfohc;
    } else {
      zuodaInfo = [];
    }
    //多选
    var mulZuoDaInfohc = wx.getStorageSync('mulZuoDaInfo')
    //console.log('onLoad方法缓存中mulZuoDaInfo的长度' + zuodaInfo.length)
    if (mulZuoDaInfohc.length > 0) {
      mulZuoDaInfo = mulZuoDaInfohc;
    } else {
      mulZuoDaInfo = [];
    }
    //传递后台答卷
    var questionArrayshc = wx.getStorageSync('questionArrays1')
    //console.log('onLoad方法缓存中questionArrays1的长度' + questionArrayshc.length)
    if (questionArrayshc.length > 0) {
      questionArrays1 = questionArrayshc;
      let tempQuestionArrays = questionArrayshc;
      let tempQuestionInfo = questionArrayshc[0];
      let tempOptionInfo = questionArrayshc[0].options;
      let tempOptionInfo2 = JSON.parse(tempOptionInfo);
      if (tempQuestionInfo.dictLabel == "单选题" || tempQuestionInfo.dictLabel == "判断题"){
        if (zuodaInfo.length > 0) {
          //console.log('第一题，单选答案大于0')
          for (let i = 0; i < zuodaInfo.length; i++) {
            if (tempQuestionInfo.questionInfoId === zuodaInfo[i].questionInfoId) {
              //.log('第一题选中单选试题ID为：' + tempQuestionInfo.questionInfoId)
              for (let n = 0; n < tempOptionInfo2.length; n++) {
                if (zuodaInfo[i].selectOption == tempOptionInfo2[n].prefix) {
                  tempOptionInfo2[n]['checked'] = 'true';
                }
              } 
            }
          }
        }
      }else{
        if (mulZuoDaInfo.length > 0) {
          for (let i = 0; i < mulZuoDaInfo.length; i++) {
            if (tempQuestionInfo.questionInfoId === mulZuoDaInfo[i].questionInfoId) {
              for (let n = 0; n < tempOptionInfo2.length; n++) {
                let IsSelected = mulZuoDaInfo[i].mulSelectOption.indexOf(tempOptionInfo2[n].prefix);
                if (IsSelected != -1) {
                  tempOptionInfo2[n]['checked'] = 'true';
                }
              }
            }
          }
          // console.log('第一题试题选项：' + tempOptionInfo2)
        }
      }
      that.setData({
        questionArrays: tempQuestionArrays,
        questionInfo: tempQuestionInfo,
        optionInfo: tempOptionInfo2
      })
    } else {
      questionArrays1 = [];
      app.formPost('/wx/test/get-question', {
        testpaper_id: options.testid
      }).then(res => {
        //console.log('onLoad方法与后台交互，获取question'+res.code)
        if (res.code == 200) {
          let tempQuestionArrays = res.questionList;
          let tempQuestionInfo = res.questionList[0];
          let tempOptionInfo = res.questionList[0].options;
          let tempOptionInfo1 = JSON.parse(tempOptionInfo);
          let tempOptionInfo2 = tempOptionInfo1.sort(function () {
            return Math.random() > 0.5 ? -1 : 1;
          });
          questionArrays1 = res.questionList;
          that.setData({
            questionArrays: tempQuestionArrays,
            questionInfo: tempQuestionInfo,
            optionInfo: tempOptionInfo2
          })
        }
      }).catch(e => {
        wx.showModal({
          title: e
        })
      })
    }
    clearInterval(Interval);
    //倒计时
    Interval = setInterval(function () {
      // 目标日期时间戳
      const end = Date.parse(new Date(options.endtime));
      //console.log(end)
      // 当前时间戳
      const now = Date.parse(new Date());
      // 相差的毫秒数
      const msec = end - now;
      //console.log(msec)
      // 计算时分秒数
      let hr = parseInt((msec / 1000 / 60 / 60) % 24);
      let min = parseInt((msec / 1000 / 60) % 60);
      let sec = parseInt((msec / 1000) % 60);
      // 个位数前补零
      hr = hr > 9 ? hr : "0" + hr;
      min = min > 9 ? min : "0" + min;
      sec = sec > 9 ? sec : "0" + sec;

      let tmpTime = hr + ":" + min + ":" + sec;
      if (hr == "00" && min == "00" && sec == "00") {
        clearInterval(Interval);
        //考试时间结束，强制交卷
        var empinfo = wx.getStorageSync('empinfo');
        var testpaper_id = that.data.testpaper_id;
        //var item_id = that.data.item_id;
        var total_num = that.data.questionArrays.length;
        wx.showLoading({
          title: "考试结束，数据正在提交......"
        });
        endtime = Date.parse(new Date());
        // 相差的毫秒数
        const msec1 = endtime - starttime;
        //console.log(msec)
        // 计算时分秒数
        let hr1 = parseInt((msec1 / 1000 / 60 / 60) % 24);
        let min1 = parseInt((msec1 / 1000 / 60) % 60);
        let sec1 = parseInt((msec1 / 1000) % 60);
        // 个位数前补零
        hr1 = hr1 > 9 ? hr1 : "0" + hr1;
        min1 = min1 > 9 ? min1 : "0" + min1;
        sec1 = sec1 > 9 ? sec1 : "0" + sec1;

        let testLength = hr1 + ":" + min1 + ":" + sec1;

        app.formPost('/wx/test/exam-submit', {
          employeeId: empinfo.employeeId,
          testpaper_id: testpaper_id,
          //item_id: item_id,
          total_num: total_num,
          starttime: starttime,
          endtime: endtime,
          testLength: testLength,
          zuodaInfo: zuodaInfo,
          mulZuoDaInfo: mulZuoDaInfo,
          questionArrays1: questionArrays1
        }).then(res => {
          if (res.code == 200) {
            setTimeout(function () {
              wx.hideLoading()
            }, 3000);
            wx.removeStorageSync('zuodaInfo');
            wx.removeStorageSync('mulZuoDaInfo');
            wx.removeStorageSync('questionArrays1');
            wx.removeStorageSync('endTmpTime');
            if (res.pesExcamTranscriptInfoId.length > 0) {
              var id = res.pesExcamTranscriptInfoId;
              wx.redirectTo({
                url: '/pages/result/index?id=' + id + '',
              })
            } else {
              wx.switchTab({
                url: '/pages/record/index',
              })
            }
          }
        }).catch(e => {
          wx.showModal({
            title: e
          })
        })
      }
      that.setData({
        time: tmpTime
      });
    }, 1000);
  },
  /**
   * 单选和判断答题记录添加到答题记录数组中
   */
  addZuoDa: function () {
    questionArrays1[this.data.index].eyAnswer = this.data.selectOption;
    //答案存缓存
    wx.setStorageSync('questionArrays1', questionArrays1)
    let zuoda = {
      testPaperInfoId: this.data.questionArrays[this.data.index].testPaperInfoId,
      questionInfoId: this.data.questionArrays[this.data.index].questionInfoId,
      answer: this.data.questionArrays[this.data.index].answer,
      score: this.data.questionArrays[this.data.index].score,
      selectOption: this.data.selectOption
    };
    if (zuodaInfo.length === 0) {
      zuodaInfo.push(zuoda);
      //答案存缓存
      wx.setStorageSync('zuodaInfo', zuodaInfo)
    } else {
      let noInsert = true;
      for (let i = 0; i < zuodaInfo.length; i++) {
        //找到已经答过的题，加以修改
        if (zuoda.questionInfoId === zuodaInfo[i].questionInfoId) {
          zuodaInfo[i] = zuoda;
          noInsert = false;
          //答案存缓存
          wx.setStorageSync('zuodaInfo', zuodaInfo)
          break;
        }
      }
      //没有找到到已经答过的题，添加到答题数组中
      if (noInsert) {
        zuodaInfo.push(zuoda);
        //答案存缓存
        wx.setStorageSync('zuodaInfo', zuodaInfo)
      }
    }

  },
  //单选变更
  radioChange: function (e) {
    //console.log('单选变更'+e.detail.value)
    this.setData({
      selectOption: e.detail.value
    });
    this.addZuoDa();
  },
  //多选变更
  checkboxChange(e) {
    //console.log(e.detail.value)
    this.setData({
      mulSelectOption: e.detail.value
    });
    this.mulAddZuoda();
  },
  /**
   * 添加多选题的答题记录
   */
  mulAddZuoda: function () {
    questionArrays1[this.data.index].eyAnswer = this.data.mulSelectOption;
    //答案存缓存
    wx.setStorageSync('questionArrays1', questionArrays1)
    let mulZuoDa = {
      testPaperInfoId: this.data.questionArrays[this.data.index].testPaperInfoId,
      questionInfoId: this.data.questionArrays[this.data.index].questionInfoId,
      answer: this.data.questionArrays[this.data.index].answer,
      score: this.data.questionArrays[this.data.index].score,
      mulSelectOption: this.data.mulSelectOption
    };
    if (mulZuoDaInfo.length === 0) {
      mulZuoDaInfo.push(mulZuoDa);
      //答案存缓存
      wx.setStorageSync('mulZuoDaInfo', mulZuoDaInfo)
    } else {
      let noInsert = true;
      for (let i = 0; i < mulZuoDaInfo.length; i++) {
        //找到已经答过的题，加以修改
        if (mulZuoDa.questionInfoId === mulZuoDaInfo[i].questionInfoId) {
          mulZuoDaInfo[i] = mulZuoDa;
          noInsert = false;
          //答案存缓存
          wx.setStorageSync('mulZuoDaInfo', mulZuoDaInfo)
          break;
        }
      }
      //没有找到到已经答过的题，添加到答题数组中
      if (noInsert) {
        mulZuoDaInfo.push(mulZuoDa);
        //答案存缓存
        wx.setStorageSync('mulZuoDaInfo', mulZuoDaInfo)
      }
    }

  },
  /**
   * 变更题目
   */
  changetQuestion: function (event) {
    //console.log(event)
    //校验是否答题 开始
    var checkIndex =event.currentTarget.dataset.index;
    var selecIndex = 0;
    if(checkIndex == 0){
       selecIndex =event.currentTarget.dataset.index+1;
    }else{
       selecIndex =event.currentTarget.dataset.index-1;
    }
    var answer = questionArrays1[selecIndex].eyAnswer;
    if (answer == '' || answer == null) {
       wx.showToast({
        title: '请选择答案'
      })
      return false
    }
    //校验是否答题 结束
    //渲染下一题题目以及选项
    this.setData({
      index: event.currentTarget.dataset.index
    });
    this.setData({
      questionInfo: this.data.questionArrays[this.data.index],
    });
    var tempOptionInfo1 = JSON.parse(this.data.questionArrays[this.data.index].options);
    let tempOptionInfo2 = tempOptionInfo1.sort(function () {
      return Math.random() > 0.5 ? -1 : 1;
    });
    // 该题为单选题
    if (this.data.questionInfo.dictLabel == "单选题" || this.data.questionInfo.dictLabel == "判断题") {
      //console.log('单选答案长度' + zuodaInfo.length)
      for (let i = 0; i < zuodaInfo.length; i++) {
        if (this.data.questionArrays[this.data.index].questionInfoId === zuodaInfo[i].questionInfoId) {
          //去空格
          //var strSelectOption = zuodaInfo[i].selectOption.replace(/\s+/g,"");
          for (let n = 0; n < tempOptionInfo2.length; n++) {
            if (zuodaInfo[i].selectOption == tempOptionInfo2[n].prefix) {
              tempOptionInfo2[n]['checked'] = 'true';
            }
          }
        }
      }
    } else if (this.data.questionInfo.dictLabel == "多选题") {
      for (let i = 0; i < mulZuoDaInfo.length; i++) {
        if (this.data.questionArrays[this.data.index].questionInfoId === mulZuoDaInfo[i].questionInfoId) {
          for (let n = 0; n < tempOptionInfo2.length; n++) {
            let IsSelected = mulZuoDaInfo[i].mulSelectOption.indexOf(tempOptionInfo2[n].prefix);
            if (IsSelected != -1) {
              tempOptionInfo2[n]['checked'] = 'true';
            }
          }
        }
      }
    };
    this.setData({
      optionInfo: tempOptionInfo2
    });
  },
  /**
   * 交卷
   */
  handIn: function (event) {
    //校验当前页面是否答题 开始
    //console.log(questionArrays1)
    var selecIndex =event.currentTarget.dataset.index;
   // console.log(questionArrays1)
    var answer = questionArrays1[selecIndex].eyAnswer;
    //console.log(answer)
    if (answer == '' || answer == null) {
       wx.showToast({
        title: '请选择答案'
      })
      return false
    }
    //校验是否答题 结束

    let that = this;
    var empinfo = wx.getStorageSync('empinfo');
    var testpaper_id = that.data.testpaper_id;
    var total_num = that.data.questionArrays.length;
    //未答题数量
    var kong_num = 0;
    for (var i = 0; i < questionArrays1.length; ++i) {
      if(questionArrays1[i].eyAnswer == null){
          kong_num = kong_num+1;
      }
    }
    var content1 = '确定提交试卷吗？';
    if(kong_num != 0){
      content1 = '您还有'+kong_num+'道题未进行作答，确定提交试卷吗？'
    }
    wx.showModal({
      content: content1,
      success(res) {
        if (res.confirm) {
          endtime = Date.parse(new Date());
          // 相差的毫秒数
          //console.log(endtime)
          //console.log(starttime)
          const msec = endtime - starttime;
          //console.log(msec)
          // 计算时分秒数
          let hr = parseInt((msec / 1000 / 60 / 60) % 24);
          let min = parseInt((msec / 1000 / 60) % 60);
          let sec = parseInt((msec / 1000) % 60);
          // 个位数前补零
          hr = hr > 9 ? hr : "0" + hr;
          min = min > 9 ? min : "0" + min;
          sec = sec > 9 ? sec : "0" + sec;
          let testLength = hr + ":" + min + ":" + sec;
          wx.showLoading({
            title: "数据正在提交......"
          });
          //console.log(questionArrays1)
          app.formPost('/wx/test/exam-submit', {
            employeeId: empinfo.employeeId,
            testpaper_id: testpaper_id,
            //item_id: item_id,
            total_num: total_num,
            starttime: starttime,
            endtime: endtime,
            testLength: testLength,
            zuodaInfo: zuodaInfo,
            mulZuoDaInfo: mulZuoDaInfo,
            questionArrays1: questionArrays1
          }).then(res => {
            if (res.code == 200) {
              setTimeout(function () {
                wx.hideLoading()
              }, 3000);
              wx.removeStorageSync('zuodaInfo');
              
              wx.removeStorageSync('mulZuoDaInfo');
              
              wx.removeStorageSync('questionArrays1');
              
              wx.removeStorageSync('endTmpTime');
              clearInterval(Interval);
             
              if (res.pesExcamTranscriptInfoId.length > 0) {
                
                var id = res.pesExcamTranscriptInfoId;
                wx.redirectTo({
                  url: '/pages/result/index?id=' + id + '',
                })
              } else {
                wx.switchTab({
                  url: '/pages/record/index',
                })
              }

            }
          }).catch(e => {
            wx.showModal({
              title: e
            })
          })
        } else if (res.cancel) {
          //console.log('用户点击取消')
        }

      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //单选
    // var zuodaInfohc = wx.getStorageSync('zuodaInfo')
    // console.log('onReady方法缓存中zuodaInfo的长度' + zuodaInfohc.length)
    // if (zuodaInfohc.length > 0) {
    //   zuodaInfo = zuodaInfohc;
    // } else {
    //   zuodaInfo = [];
    // }
    //多选
    // var mulZuoDaInfohc = wx.getStorageSync('mulZuoDaInfo')
    // console.log('onReady方法缓存中mulZuoDaInfo的长度' + zuodaInfo.length)
    // if (mulZuoDaInfohc.length > 0) {
    //   mulZuoDaInfo = mulZuoDaInfohc;
    // } else {
    //   mulZuoDaInfo = [];
    // }
    //传递后台答卷
    // var questionArrayshc = wx.getStorageSync('questionArrays1')
    // console.log('onReady方法缓存中questionArrays1的长度' + questionArrayshc.length)
    // if (questionArrayshc.length > 0) {
    //   questionArrays1 = questionArrayshc;
    // } else {
    //   questionArrays1 = [];
    // }

    //单选
    //zuodaInfo = [];
    //多选
    //mulZuoDaInfo = [];
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})